import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  yhbh: '',
  yhxm: '',
  yhgs: '',
  yhgroup: '',
  avatar: '',
  introduction: '',
  roles: [] // =操作权限
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_YHBH: (state, yhbh) => {
    state.yhbh = yhbh
  },
  SET_YHXM: (state, yhxm) => {
    state.yhxm = yhxm
  },
  SET_YHGS: (state, yhgs) => {
    state.yhgs = yhgs
  },
  SET_YHGROUP: (state, yhgroup) => {
    state.yhgroup = yhgroup
  },
  SET_ROLES: (state, czqx) => {
    state.roles = czqx
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { yhbh, yhmm } = userInfo
    return new Promise((resolve, reject) => {
      login({ yhbh: yhbh.trim(), yhmm: yhmm }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.access_token)
        setToken(data.access_token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('认证失败，请重新登录！')
        }

        // roles must be a non-empty array
        if (!data.czqx || data.czqx.length <= 0) {
          reject('操作权限!')
        }
        commit('SET_YHBH', data.yhbh)
        commit('SET_YHXM', data.yhxm)
        commit('SET_YHGS', data.yhgs)
        commit('SET_YHGROUP', data.yhgroup)
        commit('SET_ROLES', [data.czqx])
        commit('SET_AVATAR', data.avatar)  //设置头像
        resolve({ 'name': data.ybxm, 'roles': [data.czqx] }) // resolve中，需传递roles属性，其值为czqx
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
    commit('SET_YHBH', '')
    commit('SET_YHXM', '')
    commit('SET_YHGS', '')
    commit('SET_YHGROUP', '')
    removeToken()
    resetRouter()

    // reset visited views and cached views
    // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
